package com.bawei.module_detail.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bawei.lib_common.entity.Reply
import com.bawei.lib_common.entity.VideoCommentEntityItem
import com.bawei.module_detail.R
import com.bumptech.glide.Glide

class CommentAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object {
        private const val TYPE_COMMENT = 0      // 一级评论
        private const val TYPE_REPLY = 1        // 二级评论
        private const val TYPE_LOADING = 2      // 加载更多
    }

    private val dataList = mutableListOf<Any>()
    private val originalCommentList = mutableListOf<VideoCommentEntityItem>()
    private var onItemClickListener: ((position: Int, type: Int) -> Unit)? = null
    private var onItemLongClickListener: ((position: Int, type: Int) -> Unit)? = null
    private var onReplyClickListener: ((position: Int) -> Unit)? = null
    private var onLikeClickListener: ((position: Int, type: Int) -> Unit)? = null
    private var onLoadMoreClickListener: (() -> Unit)? = null

    // 记录展开状态
    private val expandedStates = mutableMapOf<Int, Boolean>()
    
    // 搜索过滤
    private var searchKeyword: String = ""
    private var isFiltered = false
    
    // 加载更多
    private var isLoadingMore = false
    private var hasMoreData = true

    fun setOnItemClickListener(listener: (position: Int, type: Int) -> Unit) {
        onItemClickListener = listener
    }

    fun setOnItemLongClickListener(listener: (position: Int, type: Int) -> Unit) {
        onItemLongClickListener = listener
    }

    fun setOnReplyClickListener(listener: (position: Int) -> Unit) {
        onReplyClickListener = listener
    }

    fun setOnLikeClickListener(listener: (position: Int, type: Int) -> Unit) {
        onLikeClickListener = listener
    }
    
    fun setOnLoadMoreClickListener(listener: () -> Unit) {
        onLoadMoreClickListener = listener
    }

    override fun getItemViewType(position: Int): Int {
        return when (dataList[position]) {
            is VideoCommentEntityItem -> TYPE_COMMENT
            is Reply -> TYPE_REPLY
            is String -> TYPE_LOADING
            else -> TYPE_COMMENT
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            TYPE_COMMENT -> {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.comment_item, parent, false)
                CommentViewHolder(view)
            }
            TYPE_REPLY -> {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.comment_two_item, parent, false)
                ReplyViewHolder(view)
            }
            TYPE_LOADING -> {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.item_loading_more, parent, false)
                LoadingViewHolder(view)
            }
            else -> {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.comment_item, parent, false)
                CommentViewHolder(view)
            }
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is CommentViewHolder -> {
                val item = dataList[position] as VideoCommentEntityItem
                holder.bind(item, position)
            }
            is ReplyViewHolder -> {
                val item = dataList[position] as Reply
                holder.bind(item, position)
            }
            is LoadingViewHolder -> {
                holder.bind()
            }
        }
    }

    override fun getItemCount(): Int = dataList.size

    /**
     * 设置评论数据
     */
    fun setCommentData(comments: List<VideoCommentEntityItem>) {
        originalCommentList.clear()
        originalCommentList.addAll(comments)
        buildDataList()
    }

    /**
     * 刷新评论列表
     */
    fun refreshCommentList(comments: List<VideoCommentEntityItem>) {
        // 保存当前展开状态
        val currentExpandedStates = expandedStates.toMutableMap()
        
        // 更新原始数据
        originalCommentList.clear()
        originalCommentList.addAll(comments)
        
        // 重新构建数据列表
        buildDataList()
    }
    
    /**
     * 构建数据列表
     */
    private fun buildDataList() {
        dataList.clear()
        
        val filteredComments = if (searchKeyword.isNotEmpty()) {
            originalCommentList.filter { comment ->
                comment.nickname.contains(searchKeyword, true) || 
                comment.content.contains(searchKeyword, true) ||
                comment.replyList.any { reply ->
                    reply.nickname.contains(searchKeyword, true) || 
                    reply.content.contains(searchKeyword, true)
                }
            }
        } else {
            originalCommentList
        }
        
        filteredComments.forEach { comment ->
            // 添加一级评论
            dataList.add(comment)
            
            // 如果评论有回复且处于展开状态，添加回复
            if (comment.replyList.isNotEmpty() && (expandedStates[comment.id] ?: false)) {
                comment.replyList.forEach { reply ->
                    dataList.add(reply)
                }
            }
        }
        
        // 添加加载更多项
        if (hasMoreData && !isLoadingMore) {
            dataList.add("loading")
        }
        
        notifyDataSetChanged()
    }

    /**
     * 切换评论展开状态
     */
    fun toggleCommentExpanded(commentId: Int) {
        val isExpanded = expandedStates[commentId] ?: false
        expandedStates[commentId] = !isExpanded
        buildDataList()
    }
    
    /**
     * 搜索过滤
     */
    fun filterComments(keyword: String) {
        searchKeyword = keyword
        isFiltered = keyword.isNotEmpty()
        buildDataList()
    }
    
    /**
     * 清除搜索过滤
     */
    fun clearFilter() {
        searchKeyword = ""
        isFiltered = false
        buildDataList()
    }
    
    /**
     * 设置加载更多状态
     */
    fun setLoadingMore(loading: Boolean) {
        isLoadingMore = loading
        if (!loading && hasMoreData) {
            buildDataList()
        }
    }
    
    /**
     * 设置是否有更多数据
     */
    fun setHasMoreData(hasMore: Boolean) {
        hasMoreData = hasMore
        buildDataList()
    }

    /**
     * 添加新评论
     */
    fun addNewComment(comment: VideoCommentEntityItem) {
        originalCommentList.add(0, comment)
        buildDataList()
    }

    /**
     * 删除评论
     */
    fun removeComment(commentId: Int) {
        val position = originalCommentList.indexOfFirst { it.id == commentId }
        if (position != -1) {
            originalCommentList.removeAt(position)
            buildDataList()
        }
    }
    
    /**
     * 更新评论
     */
    fun updateComment(commentId: Int, updatedComment: VideoCommentEntityItem) {
        val position = originalCommentList.indexOfFirst { it.id == commentId }
        if (position != -1) {
            originalCommentList[position] = updatedComment
            buildDataList()
        }
    }

    /**
     * 获取评论
     */
    fun getComment(position: Int): VideoCommentEntityItem? {
        return if (position in 0 until dataList.size && dataList[position] is VideoCommentEntityItem) {
            dataList[position] as VideoCommentEntityItem
        } else null
    }

    /**
     * 获取回复
     */
    fun getReply(position: Int): Reply? {
        return if (position in 0 until dataList.size && dataList[position] is Reply) {
            dataList[position] as Reply
        } else null
    }

    /**
     * 获取数据大小
     */
    fun getSize(): Int = dataList.size
    
    /**
     * 获取原始评论数量
     */
    fun getOriginalCommentCount(): Int = originalCommentList.size
    
    /**
     * 是否处于过滤状态
     */
    fun isFiltered(): Boolean = isFiltered

    /**
     * 一级评论ViewHolder
     */
    inner class CommentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val iv: ImageView = itemView.findViewById(R.id.commit_iv)
        private val name: TextView = itemView.findViewById(R.id.comment_name)
        private val content: TextView = itemView.findViewById(R.id.comment_content)
        private val likeCount: TextView = itemView.findViewById(R.id.comment_num)
        private val likeBtn: ImageView = itemView.findViewById(R.id.commit_iv_love)
        private val replyBtn: TextView = itemView.findViewById(R.id.c)
        private val more: LinearLayout = itemView.findViewById(R.id.comment_more)
        private val expandText: TextView = itemView.findViewById(R.id.expand_text)

        init {
            // 设置点击事件
            itemView.setOnClickListener {
                onItemClickListener?.invoke(adapterPosition, TYPE_COMMENT)
            }
            
            itemView.setOnLongClickListener {
                onItemLongClickListener?.invoke(adapterPosition, TYPE_COMMENT)
                true
            }
            
            replyBtn.setOnClickListener {
                onReplyClickListener?.invoke(adapterPosition)
            }
            
            likeBtn.setOnClickListener {
                onLikeClickListener?.invoke(adapterPosition, TYPE_COMMENT)
            }
            
            // 添加动画效果
            itemView.startAnimation(AnimationUtils.loadAnimation(itemView.context, R.anim.item_animation_fall_down))
        }

        fun bind(item: VideoCommentEntityItem, position: Int) {
            // 设置头像
            Glide.with(itemView.context)
                .load(if (item.userlogo.isNotEmpty()) item.userlogo else R.drawable.sunrise)
                .circleCrop()
                .into(iv)

            // 设置用户名和内容
            name.text = if (item.nickname.isNotEmpty()) item.nickname else "最帅黑大帅"
            content.text = if (item.content.isNotEmpty()) item.content else "高考加油！！！"
            
            // 设置点赞数量
            likeCount.text = item.agreenum.toString()

            // 处理回复列表
            if (item.replyList.isNotEmpty()) {
                val isExpanded = expandedStates[item.id] ?: false
                
                // 更新展开/收起按钮文本
                expandText.text = if (isExpanded) "收起回复" else "展开回复(${item.replyList.size})"
                
                // 显示展开按钮
                more.visibility = View.VISIBLE
                
                // 点击展开/收起
                more.setOnClickListener {
                    toggleCommentExpanded(item.id)
                }
            } else {
                // 没有回复时隐藏展开按钮
                more.visibility = View.GONE
            }
        }
    }

    /**
     * 二级评论ViewHolder
     */
    inner class ReplyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val iv: ImageView = itemView.findViewById(R.id.commit_iv)
        private val name: TextView = itemView.findViewById(R.id.comment_name)
        private val content: TextView = itemView.findViewById(R.id.comment_content)
        private val likeCount: TextView = itemView.findViewById(R.id.comment_num)
        private val likeBtn: ImageView = itemView.findViewById(R.id.commit_iv_love)
        private val replyBtn: TextView = itemView.findViewById(R.id.comment_send)
        private val timeText: TextView = itemView.findViewById(R.id.comment_time)

        init {
            // 设置点击事件
            itemView.setOnClickListener {
                onItemClickListener?.invoke(adapterPosition, TYPE_REPLY)
            }
            
            itemView.setOnLongClickListener {
                onItemLongClickListener?.invoke(adapterPosition, TYPE_REPLY)
                true
            }
            
            replyBtn.setOnClickListener {
                onReplyClickListener?.invoke(adapterPosition)
            }
            
            likeBtn.setOnClickListener {
                onLikeClickListener?.invoke(adapterPosition, TYPE_REPLY)
            }
            
            // 添加动画效果
            itemView.startAnimation(AnimationUtils.loadAnimation(itemView.context, R.anim.item_animation_from_right))
        }

        fun bind(item: Reply, position: Int) {
            // 设置头像
            Glide.with(itemView.context)
                .load(if (item.userlogo.isNotEmpty()) item.userlogo else R.drawable.sunrise)
                .circleCrop()
                .into(iv)

            // 设置用户名和内容
            name.text = if (item.nickname.isNotEmpty()) item.nickname else "最帅黑大帅"
            content.text = if (item.content.isNotEmpty()) item.content else "高考加油！！！"
            
            // 设置点赞数量
            likeCount.text = item.agreenum.toString()
            
            // 设置时间
            if (item.createtime.isNotEmpty()) {
                timeText.text = item.createtime
                timeText.visibility = View.VISIBLE
            } else {
                timeText.visibility = View.GONE
            }
        }
    }
    
    /**
     * 加载更多ViewHolder
     */
    inner class LoadingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val loadingText: TextView = itemView.findViewById(R.id.loading_text)
        
        init {
            itemView.setOnClickListener {
                onLoadMoreClickListener?.invoke()
            }
        }
        
        fun bind() {
            loadingText.text = if (isLoadingMore) "正在加载..." else "点击加载更多"
        }
    }
}